package tree.tree2.symmetry.BinarySearchTree;

import tree.TreeNode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ClassName FindMode
 * @Description TODO
 * @Author lenovo
 * @Date 2023-05-08 9:49
 * @Version 1.0
 * @Comment Magic. Do not touch.
 * If this comment is removed. the program will blow up
 */
public class FindMode {
    /**
     * 501. 二叉搜索树中的众数
     * 给你一个含重复值的二叉搜索树（BST）的根节点 root ，找出并返回 BST 中的所有 众数（即，出现频率最高的元素）。
     * <p>
     * 如果树中有不止一个众数，可以按 任意顺序 返回。
     * <p>
     * 假定 BST 满足如下定义：
     * <p>
     * 结点左子树中所含节点的值 小于等于 当前节点的值
     * 结点右子树中所含节点的值 大于等于 当前节点的值
     * 左子树和右子树都是二叉搜索树
     *
     * @param root
     * @return
     */
    public int[] findMode(TreeNode root) {
        Map<Integer, Integer> hashMap = new HashMap<>();

        inOrder(root, hashMap);

        List<Map.Entry<Integer, Integer>> topList = hashMap.entrySet().stream().sorted((x, y) -> y.getValue() - x.getValue()).collect(Collectors.toList());

        List<Integer> result = new ArrayList<>();
        Integer value = topList.get(0).getValue();
        result.add(topList.get(0).getKey());
        for (int i = 1; i < topList.size(); i++) {
            if (topList.get(i).getValue() == value) {
                result.add(topList.get(i).getKey());
            }else{
                break;
            }
        }
        int[] ints = result.stream().mapToInt(x -> x).toArray();
        return ints;
    }

    private void inOrder(TreeNode root, Map<Integer, Integer> hashMap) {
        if (root == null) return;

        inOrder(root.left, hashMap);
        hashMap.put(root.val, hashMap.getOrDefault(root.val, 0) + 1);
        inOrder(root.right, hashMap);
    }

    public static void main(String[] args) {
        TreeNode treeNode = new TreeNode(2);
        treeNode.left = new TreeNode(1);
        treeNode.left.left = new TreeNode(1);
        treeNode.right = new TreeNode(2);
        FindMode findMode = new FindMode();
        int[] mode = findMode.findMode(treeNode);
        for (int i = 0; i < mode.length; i++) {
            System.out.println(mode[i]);
        }
    }
}